Skip to content

About Deep copying and shallow copying#18

Open
Butcher3Years wants to merge 1 commit intoSmart-pointers----Its-Typesfrom
Copying--Copying-Constructor
Open

About Deep copying and shallow copying#18
Butcher3Years wants to merge 1 commit intoSmart-pointers----Its-Typesfrom
Copying--Copying-Constructor

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

Copy Constructors – The Silent Killer I Slaughtered 🪓💀

From The Cherno's C++ series (the episodes where he loses his mind over shallow vs deep copy).
This branch is my battlefield against the most dangerous default behavior in C++: the auto-generated copy constructor.

What the Fuck is a Copy Constructor?

It's the special constructor that gets called when you create a new object as a copy of an existing one.

Entity e1(10, 20);
Entity e2 = e1;          // ← copy constructor called here
Entity e3(e1);           // ← also copy ctor



class Entity {
public:
    int* data;          // raw pointer – classic trap

    Entity(int value) {
        data = new int(value);
    }

    ~Entity() {
        delete data;    // boom when double delete
    }
};

Entity e1(42);
Entity e2 = e1;         // default copy ctor: e2.data = e1.data (same pointer!)


Result:

e1 dies → delete data
e2 still points to deleted memory → dangling pointer
e2 dies → delete same address again → double free crash

Cherno:
"This is why default copy constructor is evil when you have raw resources.
Shallow copy = shared pointers = death."



Default copy = shallow → deadly with raw pointers/resources
Deep copy = manual allocation + copy in copy ctor
Rule of Zero = use RAII (unique_ptr, vector, string) → no manual copy functions
Copy elision / RVO = compiler often skips copy ctor when returning by value — free performance
Self-assignment check in operator=: if (this == &other) return *this;



Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant